package com.atguigu.gmall.payment.service;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.atguigu.gmall.model.enums.PaymentType;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.payment.config.AlipayConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: 李旭
 * @create: 2021-07-26 15:30
 **/
@Service
public class AlipayServiceImpl implements AlipayService {


    @Autowired
    private PaymentService paymentService;
    @Autowired
    private AlipayClient alipayClient;
    //统一收单下单并支付页面接口
    @Override
    public String submit(Long orderId) {
        //1:生成支付表 银行流水
        PaymentInfo paymentInfo = paymentService.insert(orderId, PaymentType.ALIPAY);
        //2:统一收单下单并页面支付接口
        //Aliay客户端
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        Map<String,Object> params = new HashMap<>();
        params.put("out_trade_no",paymentInfo.getOutTradeNo());
        params.put("product_code","FAST_INSTANT_TRADE_PAY");
        params.put("total_amount",paymentInfo.getTotalAmount());
        params.put("subject",paymentInfo.getSubject());
        request.setBizContent(JSONObject.toJSONString(params));
        //同步通知
        request.setReturnUrl(AlipayConfig.return_payment_url);
        //异步通知
        request.setNotifyUrl(AlipayConfig.notify_payment_url);

        AlipayTradePagePayResponse response = null;
        try {
            response = alipayClient.pageExecute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
            System.out.println(response.getBody());
            return response.getBody();
        } else {
            System.out.println("调用失败");
            System.out.println(response.getBody());
            return null;
        }
    }
}
